<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\UserOrder;
use app\admin\model\User;
use app\admin\model\Product;
use app\admin\model\Prize;
use app\admin\model\PrizeUser;
use app\admin\model\ProductMessage;
use app\admin\model\DistributeTask;
use app\admin\model\ChatMessage;
use app\admin\model\OrderLog;
use app\admin\model\AreaWorldwide;
use think\Db;
use think\Exception;

class Dingshi extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }
    //卖家包邮-72小说后，买家自动确认收货
    public function order_complete(){
        $time=time()-3600*24*3;
        UserOrder::where(array('status'=>3,'ship_type'=>1,'shipping_fee'=>0,'delivery_time'=>array('lt',$time)))->save(array('status'=>5,'	recieve_time'=>time()));
        exit('order to complete over');
    }
    //买家包邮-72小时未确认发货-则转回积分
    public function auto_back(){
        $time=time()-3600*24*3;
        $orders=UserOrder::where(array('status'=>2,'ship_type'=>1,'shipping_fee'=>1,'ship_num'=>array('neq',''),'delivery_time'=>array('lt',$time)))->select();
        if($orders){
            foreach($orders as $a=>$b){
                $product=Product::where(array('id'=>$b['product_id']))->find();
                ProductMessage::add(array('product_id'=>$b['product_id'],'message_id'=>0,'title'=>'卖家'.$user['nickname'].'未确认发货【'.$product['title'].'】，积分退回','user_id'=>$b['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
                UserOrder::where(array('id'=>$b['id']))->save(array('status'=>-1,'reason'=>'卖家发货超时'));

                roseandlog($b['user_id'],$b['total_money'],18,'订单超时，退回交易额');
            
            }
        }
        exit('order to back over');
    }


    //未支付订单自动取消
    public function no_payment(){
        $time=time()-900;
        //未支付订单
        $where = ['status'=>1,'add_time'=>['<',$time],'ship_type'=>1];
        $orders=UserOrder::where($where)->select();
 
        if($orders){
            foreach($orders as $a=>$b){
                UserOrder::where(array('id'=>$b['id']))->update(array('status'=>-1));
                Product::where(array('id'=>$b['product_id']))->update(array('is_sale'=>0));
            }
        }
        exit('order to complete over');
    }

    //已发货订单，48小时发送短息提醒   72小时候自动确认收货
    public function auto_recieve(){
        $time2=time()-3600*24*2;
        $time3=time()-3600*24*3;

        //自提  未点击已发货状态
        $where = ['ship_type'=>2,'status'=>2,'add_time' => ['between', [$time2, $time3]]];
        //买家付邮  未点击预约快递状态
        $where1 = ['ship_type'=>1,'status'=>2,'add_time' => ['between', [$time2, $time3]]];
        $orders=UserOrder::where($where)
        ->whereOr(function($query) use ($where1){
            $query->where($where1);
        })->select();
        $arrIds = [];
        if($orders){
            foreach($orders as $a=>$b){
                $arrIds[] = $b['id'];
                //取消订单并发送站内消息和短信提醒
                $arr = [
                    'content' => '您有笔订单待处理,请及时查看。',
                    'user_id' => 439,
                    'add_time'=>time(),
                ];
                if($b['ship_type'] == 1){  //付邮发给卖家
                    $arr['js_user_id'] = $b['shop_id'];
                }else{  //自提发给买家
                    $arr['js_user_id'] = $b['user_id'];
                }
                $arr['sort'] = $arr['js_user_id'].'00'.$arr['user_id'];
                ChatMessage::insert($arr);

                // //发送短息
                // $res = send_mobile($mobile);
                // if($res['code'] == 1){
                //     $this->success('发送成功');
                // }else{
                //     $this->error($res['msg']);
                // }
            }
        }
        var_dump($orders);
        var_dump('<br><br>');
       
       
        //自提  已发货状态
        $where = ['ship_type'=>2,'status'=>['in','2,3'],'add_time' => ['<', $time3]];
        //买家付邮  预约快递或已发货状态
        $where1 = ['ship_type'=>1,'status'=>['in','2,3,6'],'add_time' => ['<', $time3]];
        if($arrIds){
            $where['id']=['not in',$arrIds];
            $where1['id']=['not in',$arrIds];
        }
        $orders=UserOrder::where($where)
        ->whereOr(function($query) use ($where1){
            $query->where($where1);
        })->select();
        if($orders){
            foreach($orders as $a=>$b){
                $user= User::where(['id'=>$b['user_id']])->find();
                $arr = ['user_id'=>$user['id'],'order_id'=>$b['id'],'ship_type'=>$b['ship_type'],'status'=>$b['status'],'add_time'=>date('Y-m-d H:i:s',time())];
                Db::startTrans();
                try {
                    if($b['status'] == 2){ //取消订单.
                        UserOrder::where(array('id'=>$b['id']))->update(array('status'=>-1));
                        if($b['ship_type'] == 1){
                            //如果是买家付邮则需要退运费
                            //待支付的不需要退
                            if($b['status'] == 2){
                                $arr['text'] = '买家付邮退款';
                                Pay::doOrderRefund($b,$b['pay_fee'],$user['nickname'],$arr);
                            }else{
                                $arr['text'] = '待支付订单取消';
                            }
                        }else{
                            $arr['text'] = '自提取消订单';
                            //退回积分
                            roseandlog($b['user_id'],$b['total_money'],18,'取消订单，退回');
                            $product=Product::where(array('id'=>$b['product_id']))->find();
                            ProductMessage::insert(array('product_id'=>$b['product_id'],'title'=>'买家'.$user['nickname'].'取消订单，取消发货:【'.$product['title'].'】','user_id'=>$b['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
                            Product::where(array('id'=>$b['product_id']))->update(array('is_sale'=>0));
                        }
                        
                    }else{
                        $arr['text'] = '完成订单';
                        UserOrder::where(array('id'=>$b['id']))->update(array('status'=>5,'recieve_time'=>time()));
                        $product=Product::where(array('id'=>$b['product_id']))->find();
                        if($product){
                            //首次订单完成给奖励
                            $redis = redis_init();
                            $name = 'add_score_25_'.$product['user_id'];
                            $info = $redis->get($name);
                            if(!$info){
                                //未获取过奖励则直接给奖励
                                roseandlog($product['user_id'],3,25,'首次订单完成');
                                $redis->set($name,time());
                            }
        
                            roseandlog($product['user_id'],$b['total_money'],6,'售出商品获得');
                            ProductMessage::insert(array('product_id'=>$b['product_id'],'message_id'=>0,'title'=>'自动确认收货，交易商品:【'.$product['title'].'】','user_id'=>$b['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
                        }
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
        }
        if(!empty($arr)){
            OrderLog::insert($arr);
        }
        var_dump($orders);
        exit('order to complete over');
    }

    //实时监控抽奖是否到开奖时间
    public function start_prize(){
        $where = [
            'status'=>0,
            'prize_time'=>['<=',time()]
        ];
        $list = Prize::where($where)->select();
        if($list){
            foreach ($list as &$v) {
                $where = [
                    'status'=>0,
                    'prize_id'=>$v['id']
                ];
                if($v['one_award_user_list']){
                    $one_award_user_list = explode(',',$v['one_award_user_list']);
                    $where['id'] = ['in',$one_award_user_list];
                    PrizeUser::where($where)->update(['status'=>1,'prize_grade'=>1]);
                    //中奖得积分
                    if($v['one_prize']){
                        foreach ($one_award_user_list as $one) {
                            roseandlog(PrizeUser::where('id',$one)->value('user_id'),$v['one_prize'],31,'中奖得积分');
                        }
                    }
                }
                if($v['tow_award_user_list']){
                    $tow_award_user_list = explode(',',$v['tow_award_user_list']);
                    $where['id'] = ['in',$tow_award_user_list];
                    PrizeUser::where($where)->update(['status'=>1,'prize_grade'=>2]);
                    //中奖得积分
                    if($v['tow_prize']){
                        foreach ($tow_award_user_list as $tow) {
                            roseandlog(PrizeUser::where('id',$tow)->value('user_id'),$v['tow_prize'],31,'中奖得积分');
                        }
                    }
                }
                if($v['three_award_user_list']){
                    $three_award_user_list = explode(',',$v['three_award_user_list']);
                    $where['id'] = ['in',$three_award_user_list];
                    PrizeUser::where($where)->update(['status'=>1,'prize_grade'=>3]);
                    //中奖得积分
                    if($v['three_prize']){
                        foreach ($three_award_user_list as $three) {
                            roseandlog(PrizeUser::where('id',$three)->value('user_id'),$v['three_prize'],31,'中奖得积分');
                        }
                    }
                }
                unset($where['id']);
                PrizeUser::where($where)->update(['status'=>-1]);
                Prize::where(['id'=>$v['id']])->update(['status'=>1]);
            }
        }
    }


    
    //图片压缩
    public function ysImg(){

        $info = Product::where('id',5)->find();

        $src = date('Ymd') . '/' .time().rand(1000, 9999).'.png';
        $image = \think\Image::open($info['video_img']);
        // 按照原图的比例生成一个最大为600*600的缩略图替换原图
        $image->thumb(1300, 1300)->save(ROOT_PATH . 'public' . DS . 'uploads/'.$src);

        dd($src);
    }



    //推送离线消息
    public function sendLxMessage(){
        
    }



    //处理文件数据录入数据库
    public function area_worldwide(){
        $file = file_get_contents('worldAddress.txt');
        $rep = str_replace("\r\n", ',', $file);
        $cont = explode(',', $rep);
        $one = 0;  //对应的一级ID
        $one_name = '';  //对应的一级ID
        $tow = 0;  //对应的二级ID
        $tow_name = '';  //对应的二级ID
        for ($i = 0;$i < count($cont);$i++) {
            //判断有多少空格
            $spaceCount  = 0;
            for ($j = 0;$j < 6;$j++) {
                if($cont[$i][$j] != ' '){
                    break;
                }elseif ($cont[$i][$j] == ' ') {
                    $spaceCount += 1;
                }
            }
            $items =  explode('#', trim($cont[$i]));
            if($spaceCount == 0){
                $data = [
                    'pid' => 0,
                    'shortname'=>$items[0],
                    'name'=>$items[1],
                    'mergename'=>$items[0],
                    'level'=>0,
                ];
                $info = AreaWorldwide::where($data)->find();
                if($info){
                    $one = $info['id'];
                    $one_name = $items[0];
                    continue;
                }
                $one = AreaWorldwide::insertGetId($data);    
                $one_name = $items[0];
            }elseif($spaceCount == 2){
                $data = [
                    'pid' => $one,
                    'shortname'=>$items[0],
                    'name'=>$items[1],
                    'mergename'=>$one_name.','.$items[0],
                    'level'=>1,
                ];
                $info = AreaWorldwide::where($data)->find();
                if($info){
                    $tow = $info['id'];
                    $tow_name = $items[0];
                    continue;
                }
                $tow = AreaWorldwide::insertGetId($data); 
                $tow_name = $items[0];
            }elseif($spaceCount == 4){
                $data = [
                    'pid' => $tow,
                    'shortname'=>$items[0],
                    'name'=>$items[1],
                    'mergename'=>$one_name.','.$tow_name.','.$items[0],
                    'level'=>2,
                ];
                $info = AreaWorldwide::where($data)->find();
                if($info){
                    continue;
                }
                AreaWorldwide::insertGetId($data); 
            }
        }
    }

    
    //查询接单任务超过过期时间还未回传用户
    public function getDistributeTask(){
        $where = [
            'status'=>1,
            'receive_time'=>['<',time()-3600],
            'user_content'=>'',
        ];
        $ids = DistributeTask::where($where)->column('id');

        Db::startTrans();
            try {
                if($ids){
                    DistributeTask::where(['id'=>['in',$ids]])->update(['status'=>-2]);
                    //通过审核后管理商户余额
                   // set_shop_task_price($ids,1);
                }
                var_dump($ids);
                $where = [
                    'status'=>1,
                    'receive_time'=>['<',time()-(3600*36)],
                ];
                $ids = DistributeTask::where($where)->column('id');
            
                if($ids){
                    DistributeTask::where(['id'=>['in',$ids]])->update(['status'=>-2]);
                    //通过审核后管理商户余额
                    //set_shop_task_price($ids,1);
                }
                var_dump($ids);
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }

       
    }

    //检查帖子是否被删除
    public function examine_invitation(){
        $where = [
            'examine_time'=>['<',time()-(3600*48)],
            'is_del'=>0,
            'status'=>3
        ];
        $list = DistributeTask::where($where)->limit(0,100)->select();
        foreach ($list as $v) {
            DistributeTask::where(['id'=>$v['id']])->update(['examine_time'=>time()]);
            //查看该用户是否删除了帖子
            $title = $v['user_content'];
            if(!$title){
                continue;
            }
            $datas= [];
            if(strpos($title, 'http://') !== false){
                $res = explode('http://',$title);
                if(empty($res[1])){
                    continue;
                }
                $res = explode('，',$res[1]);
                $headers = get_headers('http://'.$res[0]); //获取重定向之后的url
                foreach ($headers as $vs) {
                    if (strpos($vs, 'Location') !== false) {
                        $res = explode('?',$vs);
                        if(empty($res[0])){
                            continue;
                        }
                        $datas = explode('/',$res[0]);
                    }
                }
            }
            if(count($datas) == 2 && $datas[1] == '404' && $v['is_del'] == 0){
                DistributeTask::where(['id'=>$v['id']])->update(['is_del'=>1]);
            }
        }
    }


    // $list = $this->model->where(['status'=>['neq',2],'appuid'=>''])->select();
    //     foreach ($list as $v) {
    //         $title = $v['user_content'];
    //         if(!$title){
    //             continue;
    //         }
    //         if (strpos($title, 'https://') !== false) {
    //             $res = explode('?',$title);
    //             if(empty($res[0])){
    //                 continue;
    //             }
    //             $datas = explode('/',$res[0]);
    //         }elseif(strpos($title, 'http://') !== false){
    //             $res = explode('http://',$title);
    //             if(empty($res[1])){
    //                 continue;
    //             }
    //             $res = explode('，',$res[1]);
    //             $headers = get_headers('http://'.$res[0]); //获取重定向之后的url
    //             foreach ($headers as $vs) {
    //                 if (strpos($vs, 'Location') !== false) {
    //                     $res = explode('?',$vs);
    //                     if(empty($res[0])){
    //                         continue;
    //                     }
    //                     $datas = explode('/',$res[0]);
    //                 }
    //             }
    //         }
    //         if(count($datas) > 2){
    //             $this->model->where(['id'=>$v['id']])->update(['appuid'=>$datas[count($datas)-1]]);
    //         }
    //     }
}